const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('searchContent 云函数被调用，参数：', event)
  
  try {
    const { 
      keyword = '',     // 搜索关键词
      type = 'activity', // 搜索类型：activity 或 goods
      limit = 20,       // 每页数量
      skip = 0          // 跳过数量
    } = event

    if (!keyword.trim()) {
      return {
        success: false,
        data: [],
        message: '搜索关键词不能为空'
      }
    }

    let result = []

    if (type === 'activity') {
      // 搜索活动
      result = await searchActivities(keyword, limit, skip)
    } else if (type === 'goods') {
      // 搜索商品
      result = await searchGoods(keyword, limit, skip)
    } else {
      return {
        success: false,
        data: [],
        message: '不支持的搜索类型'
      }
    }

    console.log(`${type}搜索完成，关键词：${keyword}，结果数量：${result.data.length}`)
    
    return result
    
  } catch (error) {
    console.error('搜索内容失败:', error)
    return {
      success: false,
      data: [],
      message: '搜索失败，请重试',
      error: error.message
    }
  }
}

/**
 * 搜索活动
 */
async function searchActivities(keyword, limit, skip) {
  try {
    const activitiesCollection = db.collection('activities')
    
    // 使用正则表达式进行模糊搜索
    const regex = new RegExp(keyword, 'i') // 'i' 表示不区分大小写
    
    const result = await activitiesCollection
      .where({
        eventName: regex  // 按活动名称模糊搜索
      })
      .orderBy('createdAt', 'desc')
      .skip(skip)
      .limit(limit)
      .get()
    
    return {
      success: true,
      data: result.data,
      total: result.data.length,
      message: '活动搜索成功'
    }
    
  } catch (error) {
    console.error('搜索活动失败:', error)
    throw error
  }
}

/**
 * 搜索商品
 */
async function searchGoods(keyword, limit, skip) {
  try {
    const goodsCollection = db.collection('goods')
    
    // 使用正则表达式进行模糊搜索
    const regex = new RegExp(keyword, 'i') // 'i' 表示不区分大小写
    
    const result = await goodsCollection
      .where({
        status: 1,    // 只搜索上架商品
        name: regex   // 按商品名称模糊搜索
      })
      .orderBy('createdAt', 'desc')
      .skip(skip)
      .limit(limit)
      .get()
    
    return {
      success: true,
      data: result.data,
      total: result.data.length,
      message: '商品搜索成功'
    }
    
  } catch (error) {
    console.error('搜索商品失败:', error)
    throw error
  }
}